package com.bruce.demo2.patterns.demo2.structural.demo06.proxy.demo3;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @PROJECT_NAME design_patterns
 * @DESCRIPTION 代理对象工厂，用来获取代理对象
 * @AUTHOR CNBruceLee
 * @DATE 2021/7/15 21:43
 */
public class ProxyFactory implements MethodInterceptor {

    private TrainStation station = new TrainStation();

    public TrainStation getProxyObject() {
        //创建Enhancer对象，类似与JDK代理中的Proxy类
        Enhancer enhancer = new Enhancer();

        //设置父类的字节码对象
        enhancer.setSuperclass(TrainStation.class);

        //设置回调函数
        enhancer.setCallback(this);

        //创建代理对象
        TrainStation proxtObject = (TrainStation) enhancer.create();
        return proxtObject;
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理点收取一些服务费用(CGLib动态代理方式)");
        Object retObj = method.invoke(station, objects);
        return retObj;
    }
}
